package cool.xinya.ess.controller;

import com.alibaba.fastjson.JSON;
import cool.xinya.ess.common.Result;
import cool.xinya.ess.service.BaseElasticService;
import cool.xinya.ess.util.ResultUtil;
import cool.xinya.ess.vo.IdxVo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

@RequestMapping("/index")
@RestController
public class ElasticIndexController {

    @Resource
    BaseElasticService baseElasticService;

    @GetMapping(value = "/")
    public Result index() {
        return ResultUtil.success();
    }

    /**
     * 创建Elastic索引
     */
    @PostMapping(value = "/createIndex")
    public Result createIndex(@RequestBody IdxVo idxVo) throws IOException {
        //索引不存在，再创建，否则不允许创建
        if (baseElasticService.isExistsIndex(idxVo.getIdxName())) {
            String idxSql = JSON.toJSONString(idxVo.getIdxSql());
            baseElasticService.createIndex(idxVo.getIdxName(), idxSql);
            return ResultUtil.success();
        } else {
            return ResultUtil.error("索引已经存在，不允许创建");
        }
    }

    /**
     * 查看所有Elastic索引
     */
    @GetMapping(value = "/catIndex")
    public Result catIndex() throws IOException {
        Map<String, Object> result = baseElasticService.catIndex();
        return ResultUtil.success(result);
    }

    /**
     * 判断索引是否存在；存在-TRUE，否则-FALSE
     */
    @GetMapping(value = "/exist/{index}")
    public Result indexExist(@PathVariable(value = "index") String index) throws IOException {
        if (baseElasticService.isExistsIndex(index)) {
            return ResultUtil.error(index + ",不存在");
        } else {
            return ResultUtil.error("索引已经存在, " + index);
        }
    }

    @GetMapping(value = "/del/{index}")
    public Result indexDel(@PathVariable(value = "index") String index) {
        try {
            if (baseElasticService.isExistsIndex(index)) {
                return ResultUtil.error(index + ",不存在");
            } else {
                baseElasticService.deleteIndex(index);
                return ResultUtil.success();
            }
        } catch (Exception e) {
            return ResultUtil.error("调用ElasticSearch 失败");
        }
    }
}
